import {useEffect, useState} from "react";
import useUpdate from "./useUpdate";
import {Message} from "element-react";


type Tag = {
  id: number;
  name: string
}
type Category = "-" | "+"
export type RecordItem = {
  tags: Tag[]
  note: string
  category: Category
  amount: string
  createdAt: string
}
type newRecordItem = Omit<RecordItem, "createdAt">
const useRecord = () => {
    const [records, setRecord] = useState<RecordItem[]>([]);
    const success = () => {
      Message({
        message: "保存成功",
        type: "success",
        duration: 1000
      });
    };
    const warning = (fn: () => string) => {
      Message({
        message: fn(),
        type: "warning",
        duration: 1000
      });
    };
    const addRecord = (newRecord: newRecordItem) => {
      const record = {...newRecord, createdAt: (new Date()).toISOString()};
      setRecord([...records, record]);
    };
    const initial = JSON.stringify(
      [
        {
          "tags": [{"id": 1, "name": "食"}],
          "note": "吃火锅",
          "category": "-",
          "amount": "199",
          "createdAt": "2021-03-25T05:50:02.643Z"
        },
        {
          "tags": [{"id": 2, "name": "行"}],
          "note": "打车",
          "category": "-",
          "amount": "66",
          "createdAt": "2021-03-24T05:50:05.731Z"
        },
        {
          "tags": [{"id": 3, "name": "工资"}],
          "note": "发工资啦",
          "category": "+",
          "amount": "8888",
          "createdAt": "2021-03-25T05:52:12.168Z"
        },
        {
          "tags": [{"id": 4, "name": "股票"}],
          "note": "其实我是根韭菜",
          "category": "+",
          "amount": "356",
          "createdAt": "2021-03-24T06:13:19.577Z"
        }]
    );

    useEffect(() => {
      setRecord(JSON.parse(window.localStorage.getItem("records") || initial));

    }, [initial]);
    useUpdate(() => {
      window.localStorage.setItem("records", JSON.stringify(records));
    }, records);
    return {records, setRecord, addRecord, success, warning};
  }


;
export default useRecord;